CODE 67. Add Binary

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/10/07/2013-10-07-CODE 67 Add Binary/

访问原文「CODE 67. Add Binary

Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
public String addBinary(String a, String b) {
// Note: The Solution object is instantiated only once and is reused by
// each test case.
char[] as = a.toCharArray();
char[] bs = b.toCharArray();
int i = as.length - 1;
int j = bs.length - 1;
int c = 0;
StringBuilder sb = new StringBuilder();
while (i >= 0 && j >= 0) {
if (0 == c) {
if ((as[i] == '0' && bs[j] == '1')
|| (as[i] == '1' && bs[j] == '0')) {
sb = sb.insert(0, '1');
c = 0;
} else if ((as[i] == '0' && bs[j] == '0')) {
sb = sb.insert(0, '0');
c = 0;
} else {
sb = sb.insert(0, '0');
c = 1;
}
} else if (1 == c) {
if ((as[i] == '0' && bs[j] == '1')
|| (as[i] == '1' && bs[j] == '0')) {
sb = sb.insert(0, '0');
c = 1;
} else if ((as[i] == '0' && bs[j] == '0')) {
sb = sb.insert(0, '1');
c = 0;
} else {
sb = sb.insert(0, '1');
c = 1;
}
}
i--;
j--;
}
while (i >= 0) {
if (0 == c) {
sb = sb.insert(0, as[i]);
c = 0;
} else if (1 == c) {
if (as[i] == '0') {
sb = sb.insert(0, '1');
c = 0;
} else {
sb = sb.insert(0, '0');
c = 1;
}
}
i--;
}
while (j >= 0) {
if (0 == c) {
sb = sb.insert(0, bs[j]);
c = 0;
} else if (1 == c) {
if (bs[j] == '0') {
sb = sb.insert(0, '1');
c = 0;
} else {
sb = sb.insert(0, '0');
c = 1;
}
}
j--;
}
if (1 == c) {
sb = sb.insert(0, '1');
}
return sb.toString();
}
Jerky Lu wechat
欢迎加入微信公众号